package com.zl.csMall.util;

import com.zl.csMall.code.LoginCacheMap;
import com.zl.csMall.mine.user.po.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.UUID;

/**
 * @description: 全局工具类
 * @author: ChenNing
 * @date 2025-10-15 11:35
 */
@Slf4j
@Component
public class Util {


    /**
     * @description: 判断字符串是否为NULL或空
     * @author ChenNing
     * @date: 2025-06-25 14:11
     */
    public static boolean isNullOrEmpty(String str){
        return (str == null || str.trim().equals("") || str.isEmpty());
    }

    /**
     * @description: 判断Long是否为NULL或0
     * @author ChenNing
     * @date: 2025-06-25 14:11
     */
    public static boolean isNullOrEmpty(Long data){
        return (data == null || data == 0);
    }

    /**
     * @description: 获取随机生成的Long类型ID
     * @author ChenNing
     * @date: 2025-03-19 15:06
     */
    public static long getUuId() {
        // 获取UUID的高64位并取绝对值，保证为正数
        long uniqueId = Math.abs(UUID.randomUUID().getMostSignificantBits()) % 1000000000000L;
        // 如果生成的ID长度不足12位，补充随机数
        while (String.valueOf(uniqueId).length() < 12) {
            uniqueId = uniqueId * 10 + new Random().nextInt(10); // 补充随机数字
        }
        return uniqueId;
    }

    /**
     * @description: 获取TOKEN（纯随机字符串）
     * @author ChenNing
     * @date: 2025-06-13 16:57
     */
    public static String getRandomToken(){
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * @description: token校验（纯随机字符串）
     * @author ChenNing
     * @date: 2025-06-13 17:09
     */
    public static Boolean verifyRandomToken(LoginCacheMap loginCacheMap, String token){
        User user = loginCacheMap.getUser(token);
        return loginCacheMap.getAllKeys().contains(token) && user != null && user.getId() != 0;
    }

    /**
     * @description: 删除服务器的指定物理文件
     * @param filePath 服务器文件路径
     * @author ChenNing
     * @date: 2025/4/8 17:50
     */
    public static Boolean deleteFile(String filePath){
        if (Util.isNullOrEmpty(filePath)){
            return false;
        }
        File file = new File(filePath);
        try {
            FileUtils.forceDelete(file);
            return true;
        } catch (IOException e) {
            log.error("ZL-CN:【删除物理文件】文件删除异常！ --ERROR:" + e.getMessage(), e);
        }
        return false;
    }

}
